package com.ruoyi.aitwsk.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.aitcommon.anotation.ServiceLog;
import com.ruoyi.aitcommon.service.IAitEntityInfoService;
import com.ruoyi.aitcommon.service.RestAPIService;
import com.ruoyi.aitcommon.utils.EntityCache;
import com.ruoyi.aitcommon.utils.ExceptionUtils;
import com.ruoyi.aitcommon.utils.JSONResult;
import com.ruoyi.aitcommon.utils.RestServiceUtils;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;

/**
 * 威斯克MES接口封装
 * @author Administrator
 *
 */
@Service
public class WSKMesRestService {
	@Autowired
	IAitEntityInfoService infoService;
	@Autowired
	EntityCache entityCache;
	@Autowired
	RestAPIService apiService;
	
	List<Map<String,Object>> filterlist;
	
	private JSONObject restInvoke(String url, Map<String,Object> data)
			throws Exception {
		if (data==null) {
			return JSONResult.success("没有data数据");
		}

//		构造调用参数
		Map<String, Object> head = new HashMap<String, Object>();
		head.put("Content-Type", "application/x-www-form-urlencoded");
		String poststr = getPostStr(data);
		
//		调用MES OPENAPI
		String retstr = RestServiceUtils.post(url, head,poststr);

//		处理mes服务返回
		Document retdoc = XmlUtil.parseXml(retstr);
		String jsonstr = retdoc.getDocumentElement().getTextContent();
		
		JSONObject retjson = JSONObject.parseObject(jsonstr);
		if (!retjson.containsKey("isSuccess"))
			throw new Exception("返回数据错误,无[isSuccess]!");
		if (!retjson.getBoolean("isSuccess")) {
			String msg = retjson.getString("errorMsg");
			throw new Exception("MES调用报错:" + msg);
		}
		return retjson;
	}
	
	/**
	 * 查询接口封装
	 * @param context	上下文{entityName,system,usercode,password....}
	 * @param url		调用地址
	 * @param query		查询条件JSON
	 * @return			查询结果数据
	 * @throws Exception
	 */
	@ServiceLog("MES查询服务")
	public List<Map<String, Object>> query(String url, Map<String, Object> query) throws Exception {
		List<Map<String,Object>> retlist=new ArrayList<Map<String,Object>>();
//		构造调用参数
//		String poststr = getPostStr(query);
//		调用接口获取JSON
		JSONObject json=this.restInvoke(url,query);
//		处理返回值
		JSONArray datalist= json.getJSONArray("data");
		for(Object data:datalist) {
			retlist.add((Map<String,Object>)data);
		}
		return retlist;
	}
	
	@ServiceLog("MES单据保存服务")
	public List<JSONObject> docSave(Map<String, Object> context,String url, List<Map<String, Object>> datas,
			JSONObject entityInfo) throws Exception {
		List<JSONObject> retlist = new ArrayList<JSONObject>();
		
//		ExceptionUtils.checkBlankOrUndefined(context, "context为空");
		ExceptionUtils.checkBlankOrUndefined(url, "url为空");
		ExceptionUtils.checkBlankOrUndefined(entityInfo, "entityInfo为空");
		
//		预处理
		PreDeal(context, datas, entityInfo);

		for (Map<String,Object> data : filterlist) {
//			循环单条处理
			try {
//				构造接口数据
				Map<String,Object> doc=new LinkedHashMap<String,Object>();
				
//				调用 U8 接口
				JSONObject retjson = restInvoke(url, data);
//				处理实体日志和缓存
				infoService.insertAitEntityInfo(entityInfo, data, null);
//				处理返回
				retlist.add(retjson);
			} catch (Exception ex) {
//				处理实体日志和缓存-失败信息
				infoService.insertAitEntityInfo(entityInfo, data, ex);
//				处理返回
				retlist.add(JSONResult.error(ex.getMessage()));
			}
		}
		return retlist;
	}
	
	private void PreDeal(Map<String, Object> context,List<Map<String, Object>> datas, JSONObject entityInfo)
			throws Exception {
//		ExceptionUtils.checkBlankOrUndefined(context.get("headkey"), "context.headkey为空");
//		ExceptionUtils.checkBlankOrUndefined(context.get("fenge"), "context.fenge为空");
		
		// 构造AggVO
//		List<AggMap> aggvos = ListMapUtils.transAggVO(datas, context.get("headkey").toString(), context.get("fenge").toString());
		// 从缓存过滤重复数据
//		this.filterlist=entityCache.filterAggChange(entityInfo, aggvos);
		this.filterlist=entityCache.filterEntityChange(entityInfo, datas);
		
	}
	
	/**
	 * 依据map构造调用参数Str,格式 参数1=值1&参数2=值2
	 * @param data map数据
	 * @return 参数Str
	 */
	private String getPostStr(Map<String, Object> data) {
		List<String> qlist=new ArrayList<String>();
		for(String key:data.keySet()) {
			qlist.add(key+"="+data.get(key).toString());
		}
		String poststr=StrUtil.join("&", qlist);
		return poststr;
	}
}
